<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Passport extends Base_Controller{
	
	private $wx_openid = '';

	public function __construct(){
		parent::__construct();
		$this->wx_openid = $this->input->cookie('wx_openid');
	}
	
	public function index(){
		$wx_openid = $this->input->cookie('wx_openid');
		if(!$wx_openid){
			$this->load->library('Wechat/wechatjs');
			$wx_openid = $this->wechatjs->get_openid();
			$this->input->set_cookie('wx_openid', $wx_openid, 3600*24*30);
		}else{
			$this->load->model('user_model');
			$user = $this->user_model->get_row([
				'where' => [
					'wx_openid' => $wx_openid
				]
			]);
			if($user){
				redirect($this->_url['home']);
			}
		}
		$this->ci_smarty->display('passport.htm');
	}
	
	// 销毁账号，慎用
	public function destory(){
		if(!$this->wx_openid){
			show_404();
		}
		$this->load->model('user_model');
		$this->user_model->del([
			'wx_openid' => $this->wx_openid
		]);
		$this->input->set_cookie('wx_openid', '');
		$this->show_message('销毁账号成功');
	}
	
	public function submit($action){
		$this->load->model('user_model');
		$this->load->library('form_validation');
		if('reg' == $action){
			$this->submit_reg();
		}else{
			show_404();
		}
	}
	
	private function submit_reg(){
		$this->form_validation->set_rules('phone', '手机号码', 'required|valid_phone');
		$this->form_validation->set_rules('smscode', '短信验证码', 'required');
		if($this->form_validation->run() == false){
			foreach($this->form_validation->error_array() as $filed => $error){
				$this->output_json([
					'retcode' => -1,
					'message' => $error
				]);
			}
		}
		$this->load->library('myredis');
		$posts = $this->input->post();
		$phone = $posts['phone'];
		$rdskey = 'smscode_reg_'.$phone;
		if(!$posts['smscode'] || $posts['smscode'] != $this->myredis->get($rdskey)){
			$this->output_json('短信验证码不正确');
		}
		if(!$this->wx_openid){
			$this->output_json('请在微信中重新打开');
		}
		$user = $this->user_model->get_row([
			'select' => ['uid'],
			'or_where' => [
				'phone' => $phone,
				'wx_openid' => $this->wx_openid
			]
		]);
		if($user){
			$this->output_json('该手机已注册');
		}
		$data = array(
			'phone' => $phone,
			'wx_openid' => $this->wx_openid,
			'create_time' => time()
		);
		$query = $this->user_model->set($data);
		if($query){
			$this->myredis->del($rdskey);
			$this->output_json('注册成功', 0);
		}
		$this->output_json('注册失败');
	}
	
}